package logic

import (
	"context"
	"gorm.io/gorm"
	"houseRpc/house"
	"houseRpc/internal/svc"
	"houseRpc/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *house.HouseListRequest) (*house.HouseListResponse, error) {
	// todo: add your logic here and delete this line
	var houses []models.House
	var houseList []*house.ListHouses
	query := models.DB.Model(&models.House{})

	if in.MinPrice > 0 {
		query = query.Where("price >= ?", in.MinPrice)
	}

	if in.MaxPrice > 0 {
		query = query.Where("price <= ?", in.MaxPrice)
	}

	query = query.Order("created_at desc").
		Scopes(Paginate(int(in.Page), int(in.PageSize))).
		Find(&houses)

	for _, hs := range houses {

		list := house.ListHouses{
			Title:   hs.Title,
			Ads:     hs.Ads,
			Square:  hs.Square,
			Floor:   hs.Floor,
			Price:   float32(hs.Price),
			UserId:  hs.UserId,
			Status:  hs.Status,
			HouseId: int64(hs.ID),
		}
		houseList = append(houseList, &list)
	}
	return &house.HouseListResponse{
		List: houseList,
	}, nil
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
